#!/bin/bash

set -eu -o pipefail

# This is a simple shell script that uses the grpc API to edit the database rules on a remote
# IOx server. It fetches the rules, spawns your default text editor, waits until your editor quits,
# and then calls the update API with the results of your local edit.
#
# Example:
#
# ./scripts/jq_edit_db_rules localhost:1234 load_test '.rules.lifecycleRules.dropNonPersisted = true'
#
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

usage() {
  echo "$0 <host> <db_name>"
  exit 1
}

grpcurl() {
  "${SCRIPT_DIR}"/grpcurl "$@"
}

declare -a tmps
cleanup() {
  # https://stackoverflow.com/questions/7577052/bash-empty-array-expansion-with-set-u
  rm -rf ${tmps[@]+"${tmps[@]}"}
}
trap cleanup EXIT

main() {
  if [ $# -lt 2 ]; then
    usage
  fi

  local host="${1}"
  local db_name="${2}"
  # grpcurl doesn't like the http:// scheme, while influxdb client requires it
  # let's be kind to users of this script
  host="${host#http://}"

  local tmp
  tmp="$(mktemp)"
  tmps+=("${tmp}")

  local req
  read -r -d '' req <<EOF || true
    {"name": "${db_name}"}
EOF

  grpcurl -plaintext -emit-defaults -d "${req}" "${host}" \
    influxdata.iox.management.v1.ManagementService.GetDatabase \
    > "${tmp}"

  "${EDITOR:-vim}" "${tmp}"

  grpcurl -plaintext -emit-defaults -d @ "${host}" \
    influxdata.iox.management.v1.ManagementService.UpdateDatabase \
    < "${tmp}"

}
main "$@"
